package com.kunbo.controller.local;

import com.kunbo.entity.Event;
import com.kunbo.entity.User;
import com.kunbo.event.EventProducer;
import com.kunbo.service.LikeService;
import com.kunbo.util.CommunityConstant;
import com.kunbo.util.HostHolder;
import com.kunbo.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @RequestMapping(value = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(String conversationId, Model model){
        System.out.println(conversationId);
        System.out.println("atLike");
        User user = hostHolder.getUser();

        Map<String, Object> map = new HashMap<>();

        //点赞
        Map<String, String> like = likeService.like(conversationId, user.getId());
        Set<Map.Entry<String, String>> entries = like.entrySet();
        for(Map.Entry<String, String> entry : entries ){
            map.put("likeMsg", entry.getValue());
            model.addAttribute("likeMsg", entry.getValue());
        }
//        //数量
//        int likeCount = likeService.findEntityLikeCount(entityType, entityId);
        //状态
        int likeStatus = likeService.findEntityLikeStatus(conversationId, user.getId());



//        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);
        model.addAttribute("likeStatus", likeStatus);

        if(likeStatus == 1){
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setData("postId", conversationId);
            eventProducer.fireEvent(event);
        }



        return JSON.getJSONString(map);
    }
}
